<template>
  <view class="page-container">
    <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        <uni-forms-item label="活动名称" name="name" required>
          <uni-easyinput v-model="formData.name" placeholder="请输入活动名称" :disabled="isView"></uni-easyinput>
        </uni-forms-item>
        
        <uni-forms-item label="活动描述" name="description">
          <uni-easyinput 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入活动描述"
            :disabled="isView"
          ></uni-easyinput>
        </uni-forms-item>
        
        <uni-forms-item label="活动状态" name="status" required>
          <uni-data-select 
            v-model="formData.status" 
            :localdata="statusOptions" 
            :disabled="isView"
          ></uni-data-select>
        </uni-forms-item>
      </view>

      <!-- 时间设置 -->
      <view class="form-section">
        <view class="section-title">时间设置</view>
        <uni-forms-item label="开始时间" name="start_time" required>
          <uni-datetime-picker 
            v-model="formData.start_time" 
            type="datetime"
            :disabled="isView"
          >
            <template v-slot:default="{ value }">
              <uni-easyinput 
                :value="value || '请选择开始时间'" 
                placeholder="请选择开始时间"
                :disabled="true"
              ></uni-easyinput>
            </template>
          </uni-datetime-picker>
        </uni-forms-item>
        
        <uni-forms-item label="结束时间" name="end_time" required>
          <uni-datetime-picker 
            v-model="formData.end_time" 
            type="datetime"
            :disabled="isView"
          >
            <template v-slot:default="{ value }">
              <uni-easyinput 
                :value="value || '请选择结束时间'" 
                placeholder="请选择结束时间"
                :disabled="true"
              ></uni-easyinput>
            </template>
          </uni-datetime-picker>
        </uni-forms-item>
      </view>

      <!-- 优惠券设置 -->
      <view class="form-section">
        <view class="section-title">优惠券设置</view>
        <uni-forms-item label="优惠券类型" name="coupon_type" required>
          <uni-data-select 
            v-model="formData.coupon_type" 
            :localdata="couponTypeOptions"
            :disabled="isView"
          ></uni-data-select>
        </uni-forms-item>
        
        <uni-forms-item label="优惠券数量" name="coupon_count" required>
          <uni-number-box 
            v-model="formData.coupon_count" 
            :min="1" 
            :max="10000"
            :disabled="isView"
          ></uni-number-box>
        </uni-forms-item>
        
        <uni-forms-item label="每人限领" name="limit_per_user">
          <uni-number-box 
            v-model="formData.limit_per_user" 
            :min="1" 
            :max="100"
            :disabled="isView"
          ></uni-number-box>
        </uni-forms-item>
      </view>

      <!-- 参与条件 -->
      <view class="form-section">
        <view class="section-title">参与条件</view>
        <uni-forms-item label="会员等级" name="member_level">
          <uni-data-select 
            v-model="formData.member_level" 
            :localdata="memberLevelOptions"
            :disabled="isView"
          ></uni-data-select>
        </uni-forms-item>
        
        <uni-forms-item label="最低消费" name="min_consume">
          <uni-easyinput 
            v-model="formData.min_consume" 
            type="number" 
            placeholder="请输入最低消费金额（分）"
            :disabled="isView"
          ></uni-easyinput>
        </uni-forms-item>
      </view>

      <!-- 统计信息（仅查看模式显示） -->
      <view v-if="isView && activityId" class="form-section">
        <view class="section-title">统计信息</view>
        <view class="stats-grid">
          <view class="stats-item">
            <text class="stats-value">{{ statistics.participant_count || 0 }}</text>
            <text class="stats-label">参与人数</text>
          </view>
          <view class="stats-item">
            <text class="stats-value">{{ statistics.issued_count || 0 }}</text>
            <text class="stats-label">已发放</text>
          </view>
          <view class="stats-item">
            <text class="stats-value">{{ statistics.used_count || 0 }}</text>
            <text class="stats-label">已使用</text>
          </view>
          <view class="stats-item">
            <text class="stats-value">{{ statistics.conversion_rate || '0%' }}</text>
            <text class="stats-label">转化率</text>
          </view>
        </view>
      </view>
    </uni-forms>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="!isView">
      <button class="action-btn cancel-btn" @click="handleCancel">取消</button>
      <button class="action-btn submit-btn" @click="handleSubmit" :loading="submitting">
        {{ activityId ? '更新' : '创建' }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { 
  fetchCouponActivityDetail, 
  createCouponActivity, 
  updateCouponActivity,
  fetchActivityStatistics 
} from '@/api/coupon';
import { CouponType } from '@/types/coupon';
import moment from 'moment';

// 活动状态枚举
enum ActivityStatus {
  Draft = 0,    // 草稿
  Active = 1,   // 进行中
  Ended = 2,    // 已结束
  Disabled = 3  // 已禁用
}

interface ActivityFormData {
  name: string;
  description: string;
  status: ActivityStatus;
  start_time: string;
  end_time: string;
  coupon_type: CouponType;
  coupon_count: number;
  limit_per_user: number;
  member_level?: number;
  min_consume?: number;
}

const formRef = ref();
const activityId = ref<number | null>(null);
const mode = ref<'view' | 'edit' | 'create'>('create');
const submitting = ref(false);
const statistics = ref<any>({});

const formData = reactive<ActivityFormData>({
  name: '',
  description: '',
  status: ActivityStatus.Draft,
  start_time: '',
  end_time: '',
  coupon_type: CouponType.Discount,
  coupon_count: 100,
  limit_per_user: 1,
  member_level: undefined,
  min_consume: undefined,
});

const isView = computed(() => mode.value === 'view');

const statusOptions = [
  { value: ActivityStatus.Draft, text: '草稿' },
  { value: ActivityStatus.Active, text: '进行中' },
  { value: ActivityStatus.Ended, text: '已结束' },
  { value: ActivityStatus.Disabled, text: '已禁用' },
];

const couponTypeOptions = [
  { value: CouponType.Discount, text: '折扣券' },
  { value: CouponType.Cash, text: '现金券' },
  { value: CouponType.Reduction, text: '满减券' },
  { value: CouponType.Duration, text: '时长券' },
];

const memberLevelOptions = [
  { value: undefined, text: '不限制' },
  { value: 1, text: '普通会员' },
  { value: 2, text: '银卡会员' },
  { value: 3, text: '金卡会员' },
  { value: 4, text: 'VIP会员' },
];

const rules = {
  name: {
    rules: [
      { required: true, errorMessage: '请输入活动名称' },
      { minLength: 2, maxLength: 50, errorMessage: '活动名称长度在2-50个字符' }
    ]
  },
  status: {
    rules: [{ required: true, errorMessage: '请选择活动状态' }]
  },
  start_time: {
    rules: [{ required: true, errorMessage: '请选择开始时间' }]
  },
  end_time: {
    rules: [{ required: true, errorMessage: '请选择结束时间' }]
  },
  coupon_type: {
    rules: [{ required: true, errorMessage: '请选择优惠券类型' }]
  },
  coupon_count: {
    rules: [{ required: true, errorMessage: '请输入优惠券数量' }]
  },
};

const getActivityDetail = async (id: number) => {
  try {
    const res = await fetchCouponActivityDetail(id);
    Object.assign(formData, {
      ...res,
      start_time: moment(res.start_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
      end_time: moment(res.end_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
    });
    
    // 如果是查看模式，获取统计数据
    if (isView.value) {
      getActivityStatistics(id);
    }
  } catch (error) {
    console.error('获取活动详情失败:', error);
    uni.showToast({
      title: '获取活动详情失败',
      icon: 'none'
    });
  }
};

const getActivityStatistics = async (id: number) => {
  try {
    const res = await fetchActivityStatistics(id);
    statistics.value = res;
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    const dataToSubmit = {
      ...formData,
      start_time: moment(formData.start_time).unix(),
      end_time: moment(formData.end_time).unix(),
    };
    
    if (activityId.value) {
      await updateCouponActivity(activityId.value, dataToSubmit);
      uni.showToast({ title: '更新成功', icon: 'success' });
    } else {
      await createCouponActivity(dataToSubmit);
      uni.showToast({ title: '创建成功', icon: 'success' });
    }
    
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  uni.navigateBack();
};

onLoad((options: any) => {
  if (options.id) {
    activityId.value = Number(options.id);
    mode.value = options.mode === 'edit' ? 'edit' : 'view';
    
    const title = mode.value === 'edit' ? '编辑活动' : '活动详情';
    uni.setNavigationBarTitle({ title });
    
    getActivityDetail(activityId.value);
  } else {
    mode.value = 'create';
    uni.setNavigationBarTitle({ title: '创建活动' });
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  padding: 15px;
  background-color: var(--background-color);
  min-height: 100vh;
}

.form-section {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 15px;
  margin-bottom: 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--text-color-primary);
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid var(--primary-color);
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  
  .stats-item {
    text-align: center;
    padding: 15px;
    background-color: var(--background-color);
    border-radius: var(--border-radius);
    
    .stats-value {
      display: block;
      font-size: 24px;
      font-weight: bold;
      color: var(--primary-color);
      margin-bottom: 5px;
    }
    
    .stats-label {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid var(--border-color);
  gap: 15px;
  
  .action-btn {
    flex: 1;
    height: 44px;
    border-radius: var(--border-radius);
    font-size: 16px;
    border: none;
    
    &.cancel-btn {
      background-color: #f5f5f5;
      color: var(--text-color-primary);
    }
    
    &.submit-btn {
      background-color: var(--primary-color);
      color: #fff;
    }
  }
}
</style>